package com.app.buss.service;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.app.buss.R;
import com.app.buss.bean.PushMessage;
import com.app.buss.ui.ForwebActivity;
import com.app.buss.ui.SplashActivity;
import com.app.buss.utils.BaseService;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.google.gson.Gson;

import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

/**
 * Created by YuHong on 2020/11/8 0008.
 */
public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private final static String TAG = "MessagingService_";
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // FCM registration token to your app server.
        BaseService.getInstance().token = token;
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Map<String, String> data = remoteMessage.getData();
        Gson gson = new Gson();
        if (!data.isEmpty()) {
            Log.e("SAVEDMSG::::::",gson.toJson(data));
            PushMessage pushMessage = gson.fromJson(gson.toJson(data), PushMessage.class);
            PushMessage pushMessage2 = gson.fromJson(pushMessage.getData(), PushMessage.class);
            createNotification(getBaseContext(), pushMessage2);
        }

        // Check if message contains a notification payload.
        RemoteMessage.Notification notification = remoteMessage.getNotification();
        if (notification != null) {
            showNotification(remoteMessage.getNotification());
        }
    }

    private void showNotification( RemoteMessage.Notification notification) {
        Intent intent = new Intent(this, SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(notification.getTitle())
                .setContentText(notification.getBody())
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

    private void createNotification(Context context, PushMessage pushMessageModel) {
        String channelId = context.getString(R.string.app_name);
        String notificationTitle = pushMessageModel.getPushTopic();
        if (TextUtils.isEmpty(notificationTitle)) {
            notificationTitle = channelId;
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId);
        builder.setContentTitle(notificationTitle);
        builder.setContentText(pushMessageModel.getPushContent());
        builder.setAutoCancel(true);
        try {
            long createTime = Long.parseLong(pushMessageModel.getCreateTime());
            builder.setWhen(createTime);
        }catch (Exception e){
            e.printStackTrace();
        }
        String brand = Build.BRAND;
        PendingIntent intent = setPendingIntent(context, pushMessageModel);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        if (!TextUtils.isEmpty(brand) && brand.equalsIgnoreCase("samsung")) {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
            builder.setLargeIcon(bitmap);
        }
        builder.setContentIntent(intent);
        builder.setChannelId(context.getPackageName());
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            int notificationId = (int) System.currentTimeMillis();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel(context,channelId, notificationManager);
            }
            notificationManager.notify(notificationId, builder.build());
        }

    }
    private PendingIntent setPendingIntent(Context context, PushMessage data) {
        Intent intent;
        String url = data.getUrl();
        if (TextUtils.isEmpty(url)) {
            PackageManager packageManager = context.getPackageManager();
            intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
        } else {
            intent = new Intent(this, ForwebActivity.class).putExtra("url",url);
        }
        return PendingIntent.getActivity(
                context,
                1,
                intent,
                PendingIntent.FLAG_CANCEL_CURRENT
        );
    }
    @RequiresApi(Build.VERSION_CODES.O)
    private NotificationChannel createNotificationChannel(
            Context context,
            String channelId,
            NotificationManager notificationManager
    ) {
        NotificationChannel notificationChannel =
                new NotificationChannel(
                        context.getPackageName(),
                        channelId,
                        NotificationManager.IMPORTANCE_DEFAULT
                );
        notificationChannel.enableLights(true); //开启指示灯，如果设备有的话。
        notificationChannel.enableVibration(true); //开启震动
        notificationChannel.setLightColor(Color.RED); // 设置指示灯颜色
        notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);//设置是否应在锁定屏幕上显示此频道的通知
        notificationChannel.setShowBadge(true); //设置是否显示角标
        notificationChannel.setBypassDnd(true); // 设置绕过免打扰模式
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400}); //设置震动频率
        notificationChannel.setDescription(channelId);
        notificationManager.createNotificationChannel(notificationChannel);
        return notificationChannel;
    }
}
